package com.jxd.petMgr.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class EncodeFilter implements Filter {
    FilterConfig filterConfig = null;

    public void destroy() {
        filterConfig = null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //需要指定当前在访问的资源是jsp还是servlet，jsp不需要设置编码格式
        //使用了向下转型
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

//        获取当前资源路径
        String path = request.getServletPath();
        String suffix = path.substring(path.length()- 4);
        if(!".jsp".equals(suffix)){
            //取过滤器中配置的参数
            String encode =  filterConfig.getInitParameter("encode");
                    request.setCharacterEncoding(encode);
            response.setContentType("text/html;charset="+encode);
        }
        //过滤器放行，继续往下走
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        filterConfig = config;
    }

}
